/**
 * 
 */
package info.niwota.webime.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.List;
import java.util.Scanner;

/**
 * @author qiangli
 * 
 */
public class Utils {

	private static long startupTime = System.currentTimeMillis();

	/**
	 * 
	 */
	private Utils() {
	}

	public static boolean isValidEmail(String s) {
		if (isEmpty(s)) {
			return false;
		}
		int idx1 = s.indexOf('@');
		if (idx1 <= 0) {
			return false;
		}
		int idx2 = s.lastIndexOf(".");
		if (idx2 == -1 || idx1 > idx2) {
			return false;
		}
		int len = s.length();
		// domain at least 2 or more chars
		if (idx2 + 2 > len) {
			return false;
		}
		//
		return true;
	}

	public static boolean isEmpty(String s) {
		return s == null || s.equals("");
	}

	public static void parseUri(List<NVPair> result, String query,
			final String encoding) {
		if (query != null && query.length() > 0) {
			int idx = query.indexOf("?");
			if (idx > 0) {
				query = query.substring(idx + 1);
				parse(result, new Scanner(query), encoding);
			}
		}
	}

	public static void parseContent(List<NVPair> result, final String content,
			final String encoding) throws IOException {
		if (content != null && content.length() > 0) {
			parse(result, new Scanner(content), encoding);
		}
	}

	public static void parseContent(List<NVPair> result, final byte[] content,
			String encoding) throws IOException {
		if (content != null && content.length > 0) {
			parse(result, new Scanner(new String(content, encoding)), encoding);
		}
	}

	public static void parse(final List<NVPair> result, final Scanner scanner,
			final String encoding) {
		scanner.useDelimiter("&");
		while (scanner.hasNext()) {
			final String[] nvp = scanner.next().split("=");
			if (nvp.length == 0 || nvp.length > 2) {
				// throw new IllegalArgumentException("bad parameter: " +
				// Arrays.asList(nvp));
				continue; // ignore
			}
			final String name = decode(nvp[0], encoding);
			String value = null;
			if (nvp.length == 2) {
				value = decode(nvp[1], encoding);
			}
			result.add(new NVPair(name, value));
		}
	}

	public static String decode(final String content, final String encoding) {
		try {
			return URLDecoder.decode(content, encoding != null ? encoding
					: "ISO-8859-1");
		} catch (UnsupportedEncodingException problem) {
			throw new IllegalArgumentException(problem);
		}
	}

	public static String filterCookies(String pkg, String cookies) {
		if (cookies == null) {
			return null;
		}
		final String sep = ";";
		final String[] sa = cookies.split(sep);
		final String pname = pkg + ".";
		final int plen = pname.length();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < sa.length; i++) {
			String[] nvp = sa[i].split("=");
			if (nvp.length != 2) {
				continue;
			}
			String n = nvp[0];
			String v = nvp[1];
			if (n.startsWith(pname)) {
				sb.append(n.substring(plen) + "=" + v + sep);
			}
		}
		return (sb.length() > 0 ? sb.toString() : null);
	}

	public static String prefixCookies(String pkg, String cookies) {
		if (cookies == null) {
			return null;
		}
		final String sep = ";";
		final String[] sa = cookies.split(sep);
		final String pname = pkg + ".";
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < sa.length; i++) {
			String[] nvp = sa[i].split("=");
			if (nvp.length != 2) {
				continue;
			}
			String n = nvp[0];
			String v = nvp[1];
			sb.append(pname + n + "=" + v + sep);
		}
		return (sb.length() > 0 ? sb.toString() : null);
	}

	public static String parsePath(String uri) {
		if (uri == null) {
			return "/";
		}
		return uri;
	}

	public static String getCurrentUrls(int port) throws IOException {
		StringBuffer sb = new StringBuffer();

		Enumeration<?> nis = NetworkInterface.getNetworkInterfaces();
		while (nis.hasMoreElements()) {
			NetworkInterface ni = (NetworkInterface) nis.nextElement();
			Enumeration<?> iis = ni.getInetAddresses();
			while (iis.hasMoreElements()) {
				InetAddress ia = ((InetAddress) iis.nextElement());

				if (ia.isLoopbackAddress()) {
					continue;
				}
				String addr = ia.getHostAddress();
				sb.append("http://" + addr + ":" + port + "/");
				sb.append(" ");
			}
		}
		return sb.toString();
	}

	public static File transformImage(File image, File newImage, int width,
			int height) throws Exception {
		if (!newImage.exists()
				|| newImage.lastModified() < startupTime ) {
			try {
				transform(image, newImage, width, height);
			} catch (Exception e) {
				e.printStackTrace();

				newImage.delete();
				//
				throw e;
			}
		}

		return newImage;
	}

	private static void transform(File image, File thumb, int width, int height)
			throws IOException {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(image);
			out = new FileOutputStream(thumb);
			thumbnail(in, out, width, height);
			
		} finally {
			in.close();
			out.close();
		}
	}

	private static void thumbnail(InputStream in, OutputStream out, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}
}
